#!/usr/bin/env python
import os

from distutils.core import setup
from distutils.command.build_py import build_py as _build_py
from distutils.command.install_data import install_data as _install_data

from searxqt.version import __version__

ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
LOCALES_PATH = os.path.join(ROOT_PATH, 'locales')


def compileLocales():
    cmd = os.path.join(ROOT_PATH, 'utils', 'locale_tool.sh')
    cmd += " -m all"
    if os.system(cmd) != 0:
        print("Failed to compile locales.")


def genMoList():
    data_files = []
    for langDir in os.listdir(LOCALES_PATH):
        path = os.path.join(LOCALES_PATH, langDir)

        if not os.path.isdir(path):
            continue

        moPath = os.path.join(path, "LC_MESSAGES", "searx-qt.mo")

        if not os.path.exists(moPath):
            continue

        targetPath = os.path.join("share/locale", langDir, "LC_MESSAGES")

        data_files.append(
            (targetPath, [moPath])
        )

    return data_files


class build_py(_build_py):
    def run(self):
        compileLocales()
        return _build_py.run(self)


class install_data(_install_data):
    def run(self):
        if os.path.exists(LOCALES_PATH):
            self.data_files += genMoList()
        return _install_data.run(self)


setup(name='searx-qt',
      version=__version__,
      license='GPLv3',
      description=('Lightweight desktop application for Searx.'),
      author='CYBERDEViL',
      url='https://notabug.org/cyberdevil',
      packages=[
        'searxqt',
        'searxqt.widgets',
        'searxqt.models',
        'searxqt.views',
        'searxqt.core',
        'searxqt.utils'
      ],
      classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: X11 Applications :: Qt',
        'Topic :: Internet',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
        'Topic :: Internet :: WWW/HTTP'
      ],
      scripts=[
        'bin/searx-qt'
      ],
      data_files=[
        ('share/applications', ['share/searx-qt.desktop']),
        ('share/doc/searx-qt', ['COPYING', 'README.md', 'CHANGELOG.md'])
      ],
      cmdclass={
        'build_py': build_py,
        'install_data': install_data
      })
